package cn.zjutleo.village_server.util;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;

/**
 * @author : Qin Zhenghan
 * @date : Created in 2021/7/28
 * @description: AES解密工具类
 */
public class AesDecryptUtil {
    /**
     * 算法名
     */
    private static final String ALGORITHM_NAME = "AES";

    /**
     * 加密算法模式(CBC模式需添加iv)
     */
    private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS7Padding";

    /**
     * 数据解密
     *
     * @param encryptedData 目标密文
     * @param secretKey 密钥
     * @param iv 加密算法初始向量
     * @return JSON解密明文
     */
    public static JSONObject decrypt(String encryptedData, String secretKey, String iv) {
        String decryptedResult = null;
        byte[] encryptedData64 = Base64.decodeBase64(encryptedData);
        byte[] secretKey64 = Base64.decodeBase64(secretKey);
        byte[] iv64 = Base64.decodeBase64(iv);
        try {
            initSecretKey();
            decryptedResult = new String(generateDecrypt(encryptedData64, secretKey64, generateIv(iv64)));
        } catch (Exception e) {
            System.out.println("数据解密失败: " + e.getMessage());
        }
        return JSONUtil.parseObj(decryptedResult);
    }

    /**
     * 初始化密钥
     *
     * @throws NoSuchAlgorithmException
     */
    private static void initSecretKey() throws NoSuchAlgorithmException {
        Security.addProvider(new BouncyCastleProvider());
        KeyGenerator.getInstance(ALGORITHM_NAME).init(128);
    }

    /**
     * 生成iv
     *
     * @param iv 初始向量字节数据
     * @return iv加密参数
     * @throws NoSuchAlgorithmException
     * @throws InvalidParameterSpecException
     */
    private static AlgorithmParameters generateIv(byte[] iv) throws NoSuchAlgorithmException, InvalidParameterSpecException {
        AlgorithmParameters parameters = AlgorithmParameters.getInstance(ALGORITHM_NAME);
        parameters.init(new IvParameterSpec(iv));
        return parameters;
    }

    /**
     * 生成解密
     *
     * @param encryptedDataBytes 解密内容字节数据
     * @param secretKeyBytes 密钥字节数据
     * @param iv 初始向量加密参数
     * @return 解密字节数据
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidAlgorithmParameterException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    private static byte[] generateDecrypt(byte[] encryptedDataBytes, byte[] secretKeyBytes, AlgorithmParameters iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Key key = new SecretKeySpec(secretKeyBytes, ALGORITHM_NAME);
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        // 设置解密模式
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        return cipher.doFinal(encryptedDataBytes);
    }
}
